package com.ethink.platform.job;

import cn.hutool.core.date.DatePattern;
import com.ethink.framework.common.constant.CommonRespCode;
import com.ethink.framework.common.exception.BusinessException;
import com.ethink.order.api.JkyTradeLogFacade;
import com.ethink.order.api.info.JkyTradeLogInfo;
import com.ethink.order.api.request.JkyTradeLogAddRequest;
import com.ethink.order.api.request.JkyTradeLogUpdateRequest;
import com.ethink.platform.properties.PlatformJackyunProperties;
import com.ethink.platform.util.JackyunUtils;
import com.ethink.platform.util.model.JackyunOmsTradeFullInfoRequest;
import com.ethink.platform.util.model.JackyunOmsTradeFullInfoResponse;
import com.google.common.collect.Lists;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Component
public class JackyunTradeOrderSyncJob {
    private static final Integer PAGE_SIZE = 200;

    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(DatePattern.NORM_DATETIME_PATTERN);

    private static final Integer SYNC_SINGLE_BATCH_INTERVAL_DAYS = 7;

    private static final List<String> EXCLUDED_TRADE_NO_LIST = Lists.newArrayList(
            "JY202301110283", "JY202301110281", "JY202301110279", "JY202301110264", "JY202301110261", "JY202301110244", "JY202301110240",
            "JY202301110222", "JY202301110202", "JY202301110199", "JY202301110161", "JY202301110152", "JY202301110138", "JY202301110118", "JY202301110107",
            "JY202301110096", "JY202301110087", "JY202301110078", "JY202301110072", "JY202301110053", "JY202301110034", "JY202301110033", "JY202301110028",
            "JY202301110023", "JY202301110010", "JY202301101833", "JY202301101827", "JY202301101826", "JY202301101825", "JY202301101809", "JY202301101802",
            "JY202301101787", "JY202301101764", "JY202301101762", "JY202301101759", "JY202301101752", "JY202301101747", "JY202301101739", "JY202301101737",
            "JY202301101647", "JY202301101644", "JY202301101643", "JY202301101641", "JY202301101638", "JY202301101636", "JY202301101625", "JY202301101621",
            "JY202301101620", "JY202301101612", "JY202301101576", "JY202301101566", "JY202301101556", "JY202301101495", "JY202301101460", "JY202301101308",
            "JY202301101275", "JY202301101256", "JY202301101227", "JY202301101224", "JY202301101212", "JY202301101211", "JY202301101208", "JY202301101193",
            "JY202301101182", "JY202301101158", "JY202301101153", "JY202301101127", "JY202301101105", "JY202301101064", "JY202301101012", "JY202301100961",
            "JY202301100958", "JY202301100948", "JY202301100925", "JY202301100900", "JY202301100882", "JY202301100880", "JY202301100781", "JY202301100722",
            "JY202301100691", "JY202301100617", "JY202301100607", "JY202301100368", "JY202301100363", "JY202301100351", "JY202301100334", "JY202301100321",
            "JY202301100313", "JY202301100311", "JY202301100287", "JY202301100285", "JY202301100255", "JY202301100197", "JY202301100186", "JY202301100182",
            "JY202301100175", "JY202301100138", "JY202301100132", "JY202301100104", "JY202301100062", "JY202301100061", "JY202301100046", "JY202301100031",
            "JY202301100011", "JY202301100010", "JY202301100001", "JY202301092841", "JY202301092808", "JY202301092772", "JY202301092759", "JY202301092726",
            "JY202301092718", "JY202301092717", "JY202301092696", "JY202301092654", "JY202301092497", "JY202301092496", "JY202301092478", "JY202301092472",
            "JY202301092470", "JY202301092438", "JY202301092416", "JY202301092413", "JY202301092375", "JY202301092353", "JY202301092274", "JY202301092224",
            "JY202301092223", "JY202301092215", "JY202301092179", "JY202301092178", "JY202301092159", "JY202301092158", "JY202301092144", "JY202301092128",
            "JY202301092098", "JY202301091963", "JY202301091914", "JY202301091897", "JY202301091896", "JY202301091895", "JY202301091886", "JY202301091877",
            "JY202301091865", "JY202301091843", "JY202301091831", "JY202301091815", "JY202301091813", "JY202301091796", "JY202301091765", "JY202301091711",
            "JY202301091708", "JY202301091690", "JY202301091688", "JY202301091576", "JY202301091567", "JY202301091514", "JY202301091507", "JY202301091506",
            "JY202301091500", "JY202301091399", "JY202301091330", "JY202301091318", "JY202301091304", "JY202301091297", "JY202301091281", "JY202301091276",
            "JY202301091264", "JY202301091229", "JY202301091215", "JY202301091177", "JY202301091171", "JY202301091148", "JY202301091121", "JY202301091114",
            "JY202301091112", "JY202301091074", "JY202301091067", "JY202301091045", "JY202301091034", "JY202301091027", "JY202301090997", "JY202301090982",
            "JY202301090950", "JY202301090948", "JY202301090910", "JY202301090861", "JY202301090859", "JY202301090857", "JY202301090830", "JY202301090829",
            "JY202301090760", "JY202301090737", "JY202301090623", "JY202301090607", "JY202301090602", "JY202301090579", "JY202301090568", "JY202301090030",
            "JY202301090015", "JY202301090003", "JY202301081800", "JY202301081799", "JY202301081769", "JY202301081768", "JY202301081735", "JY202301081723",
            "JY202301081703", "JY202301081686", "JY202301081669", "JY202301081637", "JY202301081630", "JY202301081614", "JY202301081611", "JY202301081608",
            "JY202301081564", "JY202301081552", "JY202301081515", "JY202301081510", "JY202301081348", "JY202301081318", "JY202301081282", "JY202301081193",
            "JY202301081181", "JY202301081159", "JY202301081156", "JY202301081154", "JY202301081142", "JY202301081113", "JY202301081102", "JY202301081094",
            "JY202301081083", "JY202301081074", "JY202301081019", "JY202301080990", "JY202301080969", "JY202301080958", "JY202301080937", "JY202301080936",
            "JY202301080928", "JY202301080922", "JY202301080912", "JY202301080846", "JY202301080815", "JY202301080800", "JY202301080677", "JY202301080575",
            "JY202301080353", "JY202301080341", "JY202301080269", "JY202301080248", "JY202301080231", "JY202301080210", "JY202301080159", "JY202301080152",
            "JY202301080148", "JY202301080116", "JY202301080092", "JY202301080086", "JY202301080085", "JY202301080072", "JY202301080044", "JY202301072763",
            "JY202301072745", "JY202301072691", "JY202301072495", "JY202301072430", "JY202301072411", "JY202301072323", "JY202301072256", "JY202301072250",
            "JY202301072248", "JY202301072205", "JY202301072106", "JY202301072104", "JY202301072076", "JY202301072007", "JY202301071821", "JY202301071773",
            "JY202301071766", "JY202301071656", "JY202301071590", "JY202301071536", "JY202301071484", "JY202301071337", "JY202301071310", "JY202301071280",
            "JY202301071266", "JY202301071263", "JY202301071220", "JY202301071212", "JY202301071205", "JY202301070280", "JY202301070236", "JY202301070230",
            "JY202301070229", "JY202301070226", "JY202301070200", "JY202301070195", "JY202301070185", "JY202301070130", "JY202301070093", "JY202301070012",
            "JY202301065950", "JY202301065938", "JY202301065934", "JY202301065851", "JY202301065829", "JY202301065817", "JY202301065808", "JY202301065780",
            "JY202301065757", "JY202301065704", "JY202301065692", "JY202301065685", "JY202301065441", "JY202301065433", "JY202301065410", "JY202301065400",
            "JY202301064878", "JY202301064843", "JY202301064297", "JY202301063430", "JY202301063363", "JY202301060857", "JY202301060725", "JY202301060697",
            "JY202301060660", "JY202301060622", "JY202301060552", "JY202301060532", "JY202301060512", "JY202301060248", "JY202301060221", "JY202301060208",
            "JY202301060202", "JY202301060198", "JY202301060192", "JY202301060112", "JY202301060100", "JY202301060088", "JY202301060071", "JY202301060060",
            "JY202301060059", "JY202301060016", "JY202301056077", "JY202301056075", "JY202301056055", "JY202301056010", "JY202301055979", "JY202301055929",
            "JY202301055901", "JY202301055885", "JY202301055857", "JY202301055852", "JY202301055851", "JY202301055827", "JY202301053817", "JY202301053788",
            "JY202301053784", "JY202301053657", "JY202301053530", "JY202301053385", "JY202301053318", "JY202301053289", "JY202301053279", "JY202301053231",
            "JY202301053229", "JY202301053193", "JY202301053169", "JY202301052923", "JY202301052876", "JY202301052873", "JY202301052813", "JY202301052692",
            "JY202301052673", "JY202301052661", "JY202301052634", "JY202301050713", "JY202301050231", "JY202301050210", "JY202301050189", "JY202301050179",
            "JY202301050119", "JY202301050118", "JY202301050103", "JY202301050088", "JY202301050057", "JY202301050003", "JY202301047551", "JY202301047228",
            "JY202301046349", "JY202301046340", "JY202301046119", "JY202301044423", "JY202301044403", "JY202301044272", "JY202301044254", "JY202301044253",
            "JY202301044232", "JY202301044214", "JY202301044116", "JY202301043962", "JY202301042340", "JY202301042290", "JY202301042278", "JY202301042148",
            "JY202301040733", "JY202301040689", "JY202301040186", "JY202301040138", "JY202301040128", "JY202301040080", "JY202301040053", "JY202301038031",
            "JY202301038014", "JY202301037928", "JY202301036927", "JY202301036860", "JY202301036807", "JY202301036690", "JY202301036687", "JY202301034394",
            "JY202301034389", "JY202301030431", "JY202301030418", "JY202301024250", "JY202301024206", "JY202301023479", "JY202301023461", "JY202301021974",
            "JY202301021916", "JY202301021735", "JY202301021717", "JY202301021489", "JY202301010132", "JY202301010061", "JY202301010014", "JY202301010012",
            "JY202212313870", "JY202212313830", "JY202212313366", "JY202212313357", "JY202212313113", "JY202212310164", "JY202212310066", "JY202212303889",
            "JY202212303876", "JY202212303875", "JY202212303547", "JY202212303521", "JY202212302126", "JY202212301939", "JY202212301647", "JY202212300131",
            "JY202212292251", "JY202212292109", "JY202212291779", "JY202212291777", "JY202212291411", "JY202212291184", "JY202212290781", "JY202212290657",
            "JY202212290093", "JY202212282688", "JY202212282190", "JY202212282183", "JY202212281177", "JY202212280703", "JY202212280619", "JY202212272345",
            "JY202212271718", "JY202212271005", "JY202212270775", "JY202212270641", "JY202212262050", "JY202212260567", "JY202212251058", "JY202212250071",
            "JY202212241591", "JY202212221057", "JY202212173729", "JY202212171859", "JY202212170334", "JY202212170143", "JY202212150153", "JY202212141224",
            "JY202212140871", "JY202212095091", "JY202212090755", "JY202212040306", "JY202212030557", "JY202211252805", "JY202210090270"
    );

    @Autowired
    private JkyTradeLogFacade jkyTradeLogFacade;

    @Autowired
    private PlatformJackyunProperties platformJackyunProperties;

    @XxlJob("JackyunTradeOrderSyncJob")
    public void run() {
        log.info("====================== 吉客云销售单同步任务开始执行 ======================");
        JkyTradeLogInfo lastConsignTimeJkyTradeLogInfo = jkyTradeLogFacade.lastConsignTimeJkyTradeLog();
        String begin;
        if (lastConsignTimeJkyTradeLogInfo != null) {
            begin = lastConsignTimeJkyTradeLogInfo.getConsignTime();
        } else {
            // 首次同步吉客云最后发货时间
            begin = "2022-12-29 10:05:00";
        }
        Date beginDate = null;
        Date batchBeginDate = null;
        try {
            batchBeginDate = beginDate = DATE_FORMAT.parse(begin);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (beginDate == null) {
            throw new BusinessException(CommonRespCode.SYSTEM_ERR, "起始时间无效");
        }

        Date endDate = new Date();
        Date batchEndDate = new Date();
        Calendar calendar = Calendar.getInstance();
        // 由于吉客云接口限制，查询起止时间差不能超过7天
        // 如果查询起止时间差超过7天，则需要拆分多次同步
        if (batchEndDate.getTime() - batchBeginDate.getTime() > 7 * 24 * 60 * 60 * 1000) {
            calendar.setTime(batchBeginDate);
            calendar.add(Calendar.DAY_OF_MONTH, SYNC_SINGLE_BATCH_INTERVAL_DAYS);
            batchEndDate = calendar.getTime();
        }
        while (batchBeginDate.getTime() < endDate.getTime()) {
            if (batchEndDate.getTime() > endDate.getTime()) {
                batchEndDate = endDate;
            }
            // 单次同步
            this.syncSingleBatch(DATE_FORMAT.format(batchBeginDate), DATE_FORMAT.format(batchEndDate));

            calendar.setTime(batchBeginDate);
            calendar.add(Calendar.DAY_OF_MONTH, SYNC_SINGLE_BATCH_INTERVAL_DAYS);
            batchBeginDate = calendar.getTime();

            calendar.setTime(batchEndDate);
            calendar.add(Calendar.DAY_OF_MONTH, SYNC_SINGLE_BATCH_INTERVAL_DAYS);
            batchEndDate = calendar.getTime();
        }
        log.info("====================== 吉客云销售单同步任务执行结束 ======================");
    }

    /**
     * 单批次同步（由于吉客云接口限制，起止时间差不能超过7天）
     *
     * @param batchBegin
     * @param batchEnd
     */
    private void syncSingleBatch(String batchBegin, String batchEnd) {
        log.info("====================== {} - {}，开始同步 ======================", batchBegin, batchEnd);
        int pageIndex = 0;
        int totalResults = 0;
        while (true) {
            JackyunOmsTradeFullInfoRequest jackyunOmsTradeFullInfoRequest = new JackyunOmsTradeFullInfoRequest();
            if (pageIndex == 0) {
                jackyunOmsTradeFullInfoRequest.setHasTotal(1);
            }
            jackyunOmsTradeFullInfoRequest.setShopIds(platformJackyunProperties.getSyncTradeOrderShopIds());
            jackyunOmsTradeFullInfoRequest.setPageIndex(pageIndex);
            jackyunOmsTradeFullInfoRequest.setPageSize(PAGE_SIZE);
            jackyunOmsTradeFullInfoRequest.setStartConsignTime(batchBegin);
            jackyunOmsTradeFullInfoRequest.setEndConsignTime(batchEnd);
            JackyunOmsTradeFullInfoResponse jackyunOmsTradeFullInfoResponse = JackyunUtils.omsTradeFullInfoGet(jackyunOmsTradeFullInfoRequest);
            if (pageIndex == 0) {
                totalResults = jackyunOmsTradeFullInfoResponse.getTotalResults();
            }
            if (CollectionUtils.isEmpty(jackyunOmsTradeFullInfoResponse.getTrades())) {
                break;
            }
            int tradeSize = jackyunOmsTradeFullInfoResponse.getTrades().size();
            log.info("====================== {} - {}，共{}条数据，当前页{}条数据，第{}页 ======================", batchBegin, batchEnd, totalResults, tradeSize, pageIndex);

            jackyunOmsTradeFullInfoResponse.getTrades().forEach(trade -> {
                if (
                        (trade.getTradeStatus().equals(6000) || trade.getTradeStatus().equals(9090)) &&
                                !trade.getTradeType().equals(8) &&
                                platformJackyunProperties.getSyncTradeOrderShopIds().contains(trade.getShopId()) &&
                                !EXCLUDED_TRADE_NO_LIST.contains(trade.getTradeNo())
                ) {
                    // 只处理状态为“6000发货在途”或“9090已完成”，订单类型不是“8售后退货”，店铺为“意欣美妆海外专营店”或“海蜜淘海外专营店”，不在需要排除的订单号范围内的订单
                    JkyTradeLogInfo jkyTradeLogInfo = jkyTradeLogFacade.getJkyTradeLogByTradeNo(trade.getTradeNo());
                    if (jkyTradeLogInfo == null) {
                        // 新增
                        JkyTradeLogAddRequest jkyTradeLogAddRequest = new JkyTradeLogAddRequest();
                        // 订单主数据
                        jkyTradeLogAddRequest.setTradeNo(trade.getTradeNo());
                        jkyTradeLogAddRequest.setTradeStatus(trade.getTradeStatus());
                        jkyTradeLogAddRequest.setWarehouseCode(trade.getWarehouseCode());
                        jkyTradeLogAddRequest.setWarehouseName(trade.getWarehouseName());
                        jkyTradeLogAddRequest.setGmtCreate(trade.getGmtCreate());
                        jkyTradeLogAddRequest.setGmtModified(trade.getGmtModified());
                        jkyTradeLogAddRequest.setConsignTime(trade.getConsignTime());
                        jkyTradeLogAddRequest.setChargeCurrency(trade.getChargeCurrencyCode());
                        jkyTradeLogAddRequest.setShopId(trade.getShopId());
                        jkyTradeLogAddRequest.setShopName(trade.getShopName());
                        jkyTradeLogAddRequest.setOnlineTradeNo(trade.getOnlineTradeNo());
                        jkyTradeLogAddRequest.setTradeTime(trade.getTradeTime());
                        // 商品详情数据
                        if (CollectionUtils.isNotEmpty(trade.getGoodsDetail())) {
                            List<JkyTradeLogAddRequest.JkyTradeLogAddRequestMateItem> mateItems = new ArrayList<>();
                            trade.getGoodsDetail().forEach(goodsDetail -> {
                                JkyTradeLogAddRequest.JkyTradeLogAddRequestMateItem mateItem = new JkyTradeLogAddRequest.JkyTradeLogAddRequestMateItem();
                                mateItem.setMateSku(goodsDetail.getGoodsNo());
                                mateItem.setSellPrice(goodsDetail.getSellPrice());
                                mateItem.setSellCount(Integer.parseInt(goodsDetail.getSellCount().toString()));
                                mateItems.add(mateItem);
                            });
                            jkyTradeLogAddRequest.setItems(mateItems);
                        }
                        // 出库状态
                        jkyTradeLogAddRequest.setCkFlag(false);

                        jkyTradeLogFacade.addJkyTradeLog(jkyTradeLogAddRequest);
                    } else {
                        if (!jkyTradeLogInfo.getCkFlag()) {
                            // 更新
                            JkyTradeLogUpdateRequest jkyTradeLogUpdateRequest = new JkyTradeLogUpdateRequest();
                            jkyTradeLogUpdateRequest.setId(jkyTradeLogInfo.getId());
                            jkyTradeLogUpdateRequest.setTradeNo(trade.getTradeNo());
                            jkyTradeLogUpdateRequest.setTradeStatus(trade.getTradeStatus());
                            jkyTradeLogUpdateRequest.setWarehouseCode(trade.getWarehouseCode());
                            jkyTradeLogUpdateRequest.setWarehouseName(trade.getWarehouseName());
                            jkyTradeLogUpdateRequest.setGmtCreate(trade.getGmtCreate());
                            jkyTradeLogUpdateRequest.setGmtModified(trade.getGmtModified());
                            jkyTradeLogUpdateRequest.setConsignTime(trade.getConsignTime());
                            jkyTradeLogUpdateRequest.setChargeCurrency(trade.getChargeCurrencyCode());
                            jkyTradeLogUpdateRequest.setShopId(trade.getShopId());
                            jkyTradeLogUpdateRequest.setShopName(trade.getShopName());
                            jkyTradeLogUpdateRequest.setOnlineTradeNo(trade.getOnlineTradeNo());
                            jkyTradeLogUpdateRequest.setTradeTime(trade.getTradeTime());
                            // 商品详情数据
                            if (CollectionUtils.isNotEmpty(trade.getGoodsDetail())) {
                                List<JkyTradeLogUpdateRequest.JkyTradeLogUpdateRequestMateItem> mateItems = new ArrayList<>();
                                trade.getGoodsDetail().forEach(goodsDetail -> {
                                    JkyTradeLogUpdateRequest.JkyTradeLogUpdateRequestMateItem mateItem = new JkyTradeLogUpdateRequest.JkyTradeLogUpdateRequestMateItem();
                                    mateItem.setMateSku(goodsDetail.getGoodsNo());
                                    mateItem.setSellPrice(goodsDetail.getSellPrice());
                                    mateItem.setSellCount(Integer.parseInt(goodsDetail.getSellCount().toString()));
                                    mateItems.add(mateItem);
                                });
                                jkyTradeLogUpdateRequest.setItems(mateItems);
                            }
                            // 出库状态
                            jkyTradeLogUpdateRequest.setCkFlag(false);

                            jkyTradeLogFacade.updateJkyTradeLog(jkyTradeLogUpdateRequest);
                        }
                    }
                }
            });
            if (jackyunOmsTradeFullInfoResponse.getTrades().size() < PAGE_SIZE) {
                break;
            }
            pageIndex ++;
        }
        log.info("====================== {} - {}，同步完成 ======================", batchBegin, batchEnd);
    }
}
